<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, watch } from "vue"
import MkEditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
import { editArticle, commitArticle } from "./commit"
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  detailData: {
    type: Object,
    default: () => { }
  }
})
const emits = defineEmits(['onSuccess'])
onMounted(() => {
  const el = document.querySelector('#markdown-box')
  initEditor(el)
})
let mkEditor
const initEditor = (el) => {
  mkEditor = new MkEditor({
    el,
    height: '500px',
    previewStyle: 'vertical',
    language: 'zh-CN'
  })

  mkEditor.getMarkdown()
}

watch(() => props.detailData.content, (newVal) => {
  if (newVal) {
    mkEditor.setHTML(newVal)
  }
})

const onSubmitClick = async () => {
  if (props.detailData._id) {
    // 编辑文章
    await editArticle({
      id: props.detailData._id,
      title: props.title,
      content: mkEditor.getHTML()
    })
  } else {
    // 创建文章
    await commitArticle({
      title: props.title,
      content: mkEditor.getHTML()
    })
  }

  mkEditor.reset()
  emits('onSuccess')
}
</script>


<style lang="scss" scoped>
.markdown-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
